public class FindMaxForm {

    public int findMaxForm(String[] strs, int m, int n) {
        int length = strs.length;
        int[] zero = new int[length];
        int[] one = new int[length];
        for (int i = 0; i < length; i++) {
            String s = strs[i];
            int k = s.length();
            if (s.contains("1")) {
                one[i] = k - s.replaceAll("1", "").length();
            }
            if (s.contains("0")) {
                zero[i] = k - s.replaceAll("0", "").length();
            }
        }
        int[][][] dp = new int[length + 1][m + 1][n + 1];
        for (int i = length - 1; i >= 0; i--) {
            for (int j = 0; j < m + 1; j++) {
                for (int k = 0; k < n + 1; k++) {
                    dp[i][j][k] = dp[i + 1][j][k];
                    if (one[i] <= k && zero[i] <= j) {
                        dp[i][j][k] = Math.max(dp[i + 1][j - zero[i]][k - one[i]] + 1, dp[i][j][k]);
                    }
                }
            }
        }
        return dp[0][m][n];
    }
}
